package com.lagou.sqlSession;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;


public class ResultSetHandler<E> {

    public Object parse(Object result, Class<?> resultType) throws Exception {
        if (result instanceof ResultSet) {
            List<E> results = new ArrayList<>();
            ResultSet resultSet = (ResultSet) result;
            while (resultSet.next()) {
                E sqlResult =(E) resultType.newInstance();
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                int columnCount = resultSetMetaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    //属性名
                    String columnName = resultSetMetaData.getColumnName(i);
                    //属性值
                    Object value = resultSet.getObject(i);

                    //内省中的方法 属性描述器，为属性生成写方法 赋值
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(sqlResult,value);
                }
                results.add(sqlResult);
            }
            return results;
        } else {
            return result;
        }
    }
}
